package com.zc.im.seqsvr.handler;

import com.zc.im.common.constant.enums.ResultEnum;
import com.zc.im.common.vo.Result;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * Project：download
 * Date：2021/9/26
 * Time：11:16
 * Description：
 *
 * @author 小帅气
 * @version 1.0
 */
public class BaseHandler {


    protected Mono<ServerResponse> ok() {
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyValue(new Result<>(ResultEnum.OK));
    }


    protected <T> Mono<ServerResponse> ok(T t) {
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyValue(new Result<>(ResultEnum.OK, t));
    }

    protected <T> Mono<ServerResponse> ok(Mono<T> mono) {
        return mono.flatMap(this::ok);
    }

    protected <T> Mono<ServerResponse> ok(Flux<T> flux) {
        Result<List<T>> result = new Result<>(ResultEnum.OK, new ArrayList<>());
        return flux.flatMap(x -> {
            result.getData().add(x);
            return Mono.empty();
        }).then(Mono.just(result)).flatMap(this::ok);
    }

    protected Mono<ServerResponse> notFound() {
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyValue(new Result<>(ResultEnum.NOT_FOUND));
    }

    protected Mono<ServerResponse> badRequest() {
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyValue(new Result<>(ResultEnum.BAD_REQUEST));
    }

}
